﻿using System;
using Autofac;
using Nancy.Bootstrapper;
using QQ2564874169.WebFx.Nancy.Middleware;
using QQ2564874169.WebFx.Nancy.Web;

namespace WebDemo
{
    public static class AppExts
    {
        private static ClientKeeper _keeper;

        internal static IPipelines UseClientKeeper(this IPipelines pipelines, ClientKeepOption options = null)
        {
            options = options ?? new ClientKeepOption
            {
                          GetClientUser = param =>
                          {
                              using (var scope = AppStartup.Container.BeginLifetimeScope())
                              {
                                  using (var mapper = scope.Resolve<IClientMapper>())
                                  {
                                      return mapper.Get(param.UserId);
                                  }
                              }
                          }
                      };
            _keeper = new ClientKeeper(pipelines, options);
            return pipelines;
        }

        internal static ClientUser ClientLogin(this NancyController controller,
            string userId, DateTime? absoluteExpiration = null)
        {
            return _keeper.Keep(controller.Context, userId, absoluteExpiration);
        }

        internal static void ClientLogout(this NancyController controller)
        {
            _keeper.CancelKeep(controller.Context);
        }
    }
}